package sysDictType

import (
	"context"
	"errors"
	v1 "gf-admin/api/system/v1"
	"gf-admin/internal/consts"
	"gf-admin/internal/dao"
	"gf-admin/internal/model/do"
	"gf-admin/internal/model/entity"
	"gf-admin/internal/service"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

func init() {
	service.RegisterSysDictType(New())
}

func New() *sSysDictType {
	return &sSysDictType{}
}

type sSysDictType struct {
}

// 获取 字典类型列表
func (s *sSysDictType) SearchList(ctx context.Context, req *v1.DictTypeSearchReq) (res *v1.DictTypeSearchRes, errs error) {
	res = new(v1.DictTypeSearchRes)
	m := dao.SysDictType.Ctx(ctx)
	if req.DictName != "" {
		m = m.Where(dao.SysDictType.Columns().DictName+" like ?", "%"+req.DictName+"%")
	}
	if req.DictType != "" {
		m = m.Where(dao.SysDictType.Columns().DictType+" like ?", "%"+req.DictType+"%")
	}
	if req.Status != "" {
		m = m.Where(dao.SysDictType.Columns().Status+" = ", gconv.Int(req.Status))
	}
	total, err := m.Count()
	if err != nil {
		return nil, errors.New("获取字典类型失败:" + err.Error())
	}
	if req.PageNum == 0 {
		req.PageNum = 1
	}
	res.Total = total
	res.CurrentPage = req.PageNum
	if req.PageSize == 0 {
		req.PageSize = consts.PageSize
	}
	err = m.Page(req.PageNum, req.PageSize).
		Order(dao.SysDictType.Columns().DictId + " asc").Scan(&res.Content)
	return res, nil
}

//添加新的字典
func (s *sSysDictType) Add(ctx context.Context, req *v1.DictTypeAddReq, userId uint64) (err error) {
	err = s.ExistsDictType(ctx, req.DictType)
	if err != nil {
		return err
	}
	_, err = dao.SysDictType.Ctx(ctx).Insert(do.SysDictType{
		DictName: req.DictName,
		DictType: req.DictType,
		Status:   req.Status,
		CreateBy: userId,
		Remark:   req.Remark,
	})
	if err != nil {
		return errors.New("添加字典类型失败")
	}
	return
}

// ExistsDictType 检查类型是否已经存在
func (s *sSysDictType) ExistsDictType(ctx context.Context, dictType string, dictId ...int64) (err error) {
	m := dao.SysDictType.Ctx(ctx).Fields(dao.SysDictType.Columns().DictId).
		Where(dao.SysDictType.Columns().DictType, dictType)
	if len(dictId) > 0 {
		m = m.Where(dao.SysDictType.Columns().DictId+" !=? ", dictId[0])
	}
	res, e := m.One()
	if e != nil {
		return errors.New("sql查询出错:" + e.Error())
	}
	if !res.IsEmpty() {
		return errors.New("字典类型已存在")
	}
	return
}

//  删除字典类型
func (s *sSysDictType) Delete(ctx context.Context, dictIds []int) (errs error) {
	err := g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		discs := ([]*entity.SysDictType)(nil)
		err := dao.SysDictType.Ctx(ctx).Fields(dao.SysDictType.Columns().DictType).
			Where(dao.SysDictType.Columns().DictId+" in (?) ", dictIds).Scan(&discs)
		if err != nil {
			return errors.New("删除失败:" + err.Error())
		}

		types := garray.NewStrArray()
		for _, dt := range discs {
			types.Append(dt.DictType)
		}
		if types.Len() > 0 {
			_, err = dao.SysDictType.Ctx(ctx).TX(tx).Delete(dao.SysDictType.Columns().DictId+" in (?) ", dictIds)
			if err != nil {
				return errors.New("删除类型失败:" + err.Error())
			}
			_, err = dao.SysDictData.Ctx(ctx).TX(tx).Delete(dao.SysDictData.Columns().DictType+" in (?) ", types.Slice())
		}

		return err
	})
	return err
}

// 获取单条字典数据
func (s *sSysDictType) Get(ctx context.Context, req *v1.DictTypeGetReq) (dictType *entity.SysDictType, errs error) {
	err := dao.SysDictType.Ctx(ctx).Where(dao.SysDictType.Columns().DictId, req.DictId).Scan(&dictType)
	if err != nil {
		return nil, errors.New("获取字典类型失败:" + err.Error())
	}
	return
}

//修改字典
func (s *sSysDictType) Edit(ctx context.Context, req *v1.DictTypeEditReq, userId uint64) (err error) {
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		err = s.ExistsDictType(ctx, req.DictType, req.DictId)
		if err != nil {
			return err
		}
		dictType := (*entity.SysDictType)(nil)
		err = dao.SysDictType.Ctx(ctx).Fields(dao.SysDictType.Columns().DictType).WherePri(req.DictId).Scan(&dictType)
		if err != nil {
			return errors.New("获取字典类型失败:" + err.Error())
		}

		if dictType == nil {
			return errors.New("字典类型不存在")
		}
		//修改字典类型
		_, err = dao.SysDictType.Ctx(ctx).TX(tx).WherePri(req.DictId).Update(do.SysDictType{
			DictName: req.DictName,
			DictType: req.DictType,
			Status:   req.Status,
			UpdateBy: userId,
			Remark:   req.Remark,
		})
		if err != nil {
			return errors.New("修改字典类型失败:" + err.Error())
		}
		//修改字典数据
		_, err = dao.SysDictData.Ctx(ctx).TX(tx).Data(do.SysDictData{DictType: req.DictType}).
			Where(dao.SysDictData.Columns().DictType, dictType.DictType).Update()

		if err != nil {
			return errors.New("修改字典数据失败:" + err.Error())
		}

		return err
	})
	return
}
